﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MKAdmin.DataHelper;
using MKAdmin.DTO.Web.Common;
using MKAdmin.DTO.Web.HomePage.Pandect;
using MKAdmin.DTO.Web.Login;
using MKAdmin.IService.Web.HomePage;
using MKAdmin.ServiceImpl.Web.Common;
using MKAdmin.ToolKit;

namespace MKAdmin.ServiceImpl.Web.HomePage
{
    public class PandectService : IPandectService
    {
        /// <summary>
        /// 获取tab内容
        /// </summary>
        /// <returns></returns>
        public Result<List<GetTabContentModel>> GetTabContent(GetTabContentParameter parameter)
        {
            var list = new Result<List<GetTabContentModel>>()
            {
                data = new List<GetTabContentModel>()
            };
            using (var util = new DBHelper())
            {
                string sql = $@"
                                Select RightId TabId,SoundCodeFileName TabContentTitle
                                From dbo.PageSoundCodeRightInfo pscri With(NoLock)
                                Where RightId = {parameter.TabId} And StatusCode = 0
                                Order By OrderNo Desc";

                list.data = util.GetDataTable(sql).ToList<GetTabContentModel>();

                if (list.data != null && list.data.Count > 0)
                {
                    list.data.ForEach((q) =>
                    {
                        var fileName = q.TabContentTitle;
                        var extensionName = System.IO.Path.GetExtension(fileName);
                        switch (extensionName)
                        {
                            case ".cshtml":
                                q.CodeType = "html";
                                q.TabIcon = "/images/code_html.png";
                                break;
                            case ".js":
                                q.CodeType = "js";
                                q.TabIcon = "/images/code_js.png";
                                break;
                            default:
                                break;
                        }

                        q.TabContentTitle = System.IO.Path.GetFileName(fileName);
                        q.TabContentStr = TxtHelper.GetFileContent(fileName).data;
                    });
                }
            }

            return list;
        }


        /// <summary>
        /// 获取首页汇总数据
        /// </summary>
        /// <returns></returns>
        public Result<CollectListModel> Collect(UserInfoModel userInfo)
        {
            var list = new Result<CollectListModel>()
            {
                data = new CollectListModel()
            };
            using (var util = new DBHelper())
            {
                string kfAccountStr = CurrentUserService.GetKfAccountStr(
                    CurrentUserService.ConvertToSubAccountParameter(userInfo, EmAccountStatusCode.NorAndForbidden).data).data;
                if (string.IsNullOrWhiteSpace(kfAccountStr))
                {
                    return list;
                }
                string startDay = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                string endDay = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

                string sql = $@"
                                Declare @friendsCount Int;
                                Declare @maleFriendsCount Int;
                                Declare @femaleFriendsCount Int;
                                Declare @groupSumCount Int;
                                Declare @groupOwnerCount Int;
                                Declare @groupGroupMemberCount Int;
                                Declare @wxSumCount Int;
                                Declare @wxQRCodeCount Int;
                                Declare @wxLoginedWxCount Int;

                                SELECT @friendsCount = Sum(tmudr.friendsCount)
	                                ,@maleFriendsCount = Sum(tmudr.maleFriendsCount)
	                                ,@femaleFriendsCount = Sum(tmudr.femaleFriendsCount)
	                                ,@groupSumCount = Sum(tmudr.myGroupCount + tmudr.GroupCount)
	                                ,@groupOwnerCount = Sum(tmudr.myGroupCount)
	                                ,@groupGroupMemberCount = Sum(tmudr.myGroupMemerCount + tmudr.GroupMemerCount)
                                FROM DBO.Tb_mt_UserData_Report tmudr With(NoLock)
                                Where wxId In(
	                                Select username from dbo.Tb_mt_UserList tmul With(NoLock) 
                                        Where tmul.StatusCode In(0,1) And AgentName In ({kfAccountStr})
                                )

                                --新增好友总数
                                SELECT sex,Count(1) SumCount FROM DBO.Tb_mt_FriendList tmfl With(NoLock)
                                Left Join DBO.Tb_mt_UserList tmul With(NoLock) 
	                                On tmul.StatusCode In(0,1) And tmfl.UserName = tmul.UserName
                                Where tmul.AgentName In ({kfAccountStr})
                                And tmfl.CreateTime >= '{startDay}' And tmfl.CreateTime <= '{endDay}'
                                --排除自己
                                And tmfl.UserName != tmfl.wxid
                                Group By tmfl.sex

                                --微信总数(超级管理员才需要显示)
                                Select @wxSumCount = AuthorizWxCount 
                                From dbo.Tb_mt_AgentUser With(NoLock)
                                Where Id = {userInfo.OperatorId}
                                --扫码注册手机数
                                Select @wxQRCodeCount = Count(*) 
                                From dbo.mobile mb With(NoLock)
	                                Where mb.account_sub In({kfAccountStr})
	                                And Flag = 0
                                --登陆过
                                Select @wxLoginedWxCount = Count(Distinct(wl.wxid)) from dbo.wxLogin wl With(NoLock)
                                Left Join dbo.Tb_mt_UserList tmul With(NoLock) 
	                                On tmul.StatusCode In(0,1) And wl.wxid = tmul.wxid 
                                Where tmul.AgentName In({kfAccountStr})
                                      And wl.wxid is not null

                                SELECT IsNull(@friendsCount,0) friendsCount,IsNull(@maleFriendsCount,0) maleFriendsCount
                                    ,IsNull(@femaleFriendsCount,0) femaleFriendsCount
                                    ,IsNull(@groupSumCount,0) groupSumCount,IsNull(@groupOwnerCount,0) groupOwnerCount
	                                ,IsNull(@groupGroupMemberCount,0) groupGroupMemberCount, IsNull(@wxSumCount,0) wxSumCount
	                                ,IsNull(@wxQRCodeCount,0) wxQRCodeCount,IsNull(@wxLoginedWxCount,0) wxLoginedWxCount
                                ";

                DataSet dsResult = util.GetDataSet(sql);

                list = collectInfo(dsResult, userInfo);
            }

            return list;
        }

        /// <summary>
        /// 好友区域统计
        /// </summary>
        /// <returns></returns>
        public PagingList<FriendsAreaCollectModel> GetFriendAreaCollect(FriendsAreaCollectParameter parameter
            , UserInfoModel userInfo)
        {
            var list = new PagingList<FriendsAreaCollectModel>()
            {
                data = new List<FriendsAreaCollectModel>()
            };
            using (var util = new DBHelper())
            {
                parameter.prov = string.IsNullOrEmpty(parameter.prov) ? "" : parameter.prov;
                string kfAccountStr = CurrentUserService.GetKfAccountStr(
                    CurrentUserService.ConvertToSubAccountParameter(userInfo, EmAccountStatusCode.NorAndForbidden).data).data;
                if (string.IsNullOrWhiteSpace(kfAccountStr))
                {
                    return list;
                }
                string startDay = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                string endDay = DateTime.Now.ToString("yyyy-MM-dd 23:59:59");

                StringBuilder sql = new StringBuilder();
                sql.AppendLine("SELECT tmfl.Prov,Count(*) FriendsCount ");
                sql.AppendLine("FROM DBO.Tb_mt_FriendList tmfl With(NoLock)");
                sql.AppendLine("Left Join DBO.Tb_mt_UserList tmul With(NoLock) ");
                sql.AppendLine("    On tmfl.UserName = tmul.UserName ");
                sql.AppendLine($"Where tmul.StatusCode In(0,1) And tmul.AgentName In ({kfAccountStr})");
                sql.AppendLine("--排除自己");
                sql.AppendLine("    And tmfl.UserName != tmfl.wxid");
                if (!string.IsNullOrEmpty(parameter.prov))
                {
                    sql.AppendLine("And tmfl.Prov = @Prov");
                }
                sql.AppendLine("Group By tmfl.Prov");

                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(new SqlParameter() { ParameterName = "@Prov", DbType = DbType.String, Value = parameter.prov });

                var sqlStr = SqlPagingHelper.GetPagingSql(sql.ToString(), parameter.pageIndex, parameter.pageSize,
                       "Order By Prov Desc");
                DataTable dtResult = util.GetDataTable(sqlStr);

                if (dtResult != null && dtResult.Rows.Count > 0)
                {
                    list.count = Convert.ToInt32(dtResult.Rows[0]["TotalCount"]);
                    list.data.Add(new FriendsAreaCollectModel()
                    {
                        xAxis = dtResult.AsEnumerable().Select(q => q.Field<int>("FriendsCount")).ToList(),
                        yAxis = dtResult.AsEnumerable().Select(q => q.Field<string>("Prov")).ToList()
                    });
                }

                return list;
            }
        }

        /// <summary>
        /// 统计信息
        /// </summary>
        /// <param name="dsResult"></param>
        /// <returns></returns>
        private Result<CollectListModel> collectInfo(DataSet dsResult, UserInfoModel
    userInfo)
        {
            var list = new Result<CollectListModel>()
            {
                data = new CollectListModel()
            };


            if (dsResult != null && dsResult.Tables != null && dsResult.Tables.Count > 0)
            {
                if (dsResult.Tables.Count > 0)
                {
                    //新增好友统计
                    DataTable newFriendCollect = dsResult.Tables[0];
                    int newFriendsSumCount = 0;
                    int newFriendsMaleCount = 0;
                    int newFriendsFemaleCount = 0;

                    if (newFriendCollect != null && newFriendCollect.Rows.Count > 0)
                    {
                        for (int i = 0; i < newFriendCollect.Rows.Count; i++)
                        {
                            int sex = Convert.ToInt32(newFriendCollect.Rows[i]["sex"]);
                            int sumCount = Convert.ToInt32(newFriendCollect.Rows[i]["SumCount"]);
                            newFriendsSumCount += sumCount;
                            if (sex == 1)
                            {
                                newFriendsMaleCount = sumCount;
                            }
                            else if (sex == 2)
                            {
                                newFriendsFemaleCount = sumCount;
                            }
                        }
                    }
                    list.data.newFriendsSumCount = newFriendsSumCount;
                    list.data.newFriendsMaleCount = newFriendsMaleCount;
                    list.data.newFriendsFemaleCount = newFriendsFemaleCount;
                    list.data.newFriendsUnknownCount = list.data.newFriendsSumCount - list.data.newFriendsMaleCount - list.data.newFriendsFemaleCount;

                    if (dsResult.Tables.Count > 1)
                    {
                        DataTable groupCollect = dsResult.Tables[1];
                        if (groupCollect != null && groupCollect.Rows.Count > 0)
                        {
                            //好友统计
                            list.data.friendsSumCount = Convert.ToInt32(groupCollect.Rows[0]["friendsCount"]); ;
                            list.data.friendsMaleCount = Convert.ToInt32(groupCollect.Rows[0]["maleFriendsCount"]); ;
                            list.data.friendsFemaleCount = Convert.ToInt32(groupCollect.Rows[0]["femaleFriendsCount"]);
                            list.data.friendsUnknownCount = list.data.friendsSumCount - list.data.friendsMaleCount - list.data.friendsFemaleCount;

                            //群，群成员，微信数统计
                            list.data.groupSumCount = Convert.ToInt32(groupCollect.Rows[0]["groupSumCount"]);
                            list.data.groupOwnerCount = Convert.ToInt32(groupCollect.Rows[0]["groupOwnerCount"]);
                            list.data.groupGroupMemberCount = Convert.ToInt32(groupCollect.Rows[0]["groupGroupMemberCount"]);
                            list.data.wxQRCodeCount = Convert.ToInt32(groupCollect.Rows[0]["wxQRCodeCount"]);
                            list.data.wxLoginedWxCount = Convert.ToInt32(groupCollect.Rows[0]["wxLoginedWxCount"]);
                        }
                    }
                }
            }

            return list;
        }

        /// <summary>
        /// 下载源码日志
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public Result DownLoadCodeLog(UserInfoModel userInfo)
        {
            var result = new Result();

            using (var util = new DBHelper())
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine($@"Insert Into dbo.LoadSoundCodeLog(OperatorId,IPAddress,CreateTime)
                                  Values(@OperatorId,@IPAddress,GetDate())");

                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(new SqlParameter() { ParameterName = "@OperatorId", DbType = DbType.Int32, Value = userInfo.OperatorId });
                param.Add(new SqlParameter() { ParameterName = "@IPAddress", DbType = DbType.String, Value = IpAddressHelper.GetIpAddress().data });

                util.ExecuteQuery(sql.ToString(), CommandType.Text, param.ToArray());

                return result;
            }
        }


    }

    public class PandectTest
    {

    }
}
